<template>
  <el-row>
    <el-col :span="5" style="height: 100%; padding-left: 20px; padding-top: 20px; border-right: 1px solid #dfe6ec">
      <div class="comp-tree">
        <el-button class="comp-tr-top" type="primary" size="small" @click="handleAddTop" style="width: 100%">添加顶级节点</el-button>
        <!-- tree -->
        <el-input placeholder="输入关键字进行过滤~" v-model="filterText"> </el-input>
        <el-tree
          ref="SlotTree"
          :data="treeList"
          :props="defaultProps"
          :current-node-key="currentNodekey"
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          highlight-current
          :node-key="NODE_KEY"
          @node-click="handleNodeClick"
          style="margin-top: 1rem"
        >
          <div class="comp-tr-node" slot-scope="{ node, data }">
            <i v-if="data.parentId === '0'" class="el-icon-folder"></i>
            <i v-else class="el-icon-collection-tag"></i>
            <!-- 编辑状态 -->
            <template v-if="node.isEdit">
              <el-input v-model="data.name" autofocus size="mini" :ref="'slotTreeInput' + data[NODE_KEY]" @blur.stop="handleInput(node, data)" @keyup.enter.native="handleInput(node, data)"></el-input>
            </template>

            <!-- 非编辑状态 -->
            <template v-else>
              <!-- 名称： 新增节点增加class（is-new） -->
              <span :class="[data[NODE_KEY] < NODE_ID_START ? 'is-new' : '', 'comp-tr-node--name']">
                {{ node.label }}
              </span>

              <!-- 按钮 -->
              <el-dropdown placement="top" style="margin-left: 10%">
                <span class="el-dropdown-link">
                  <i class="el-icon-more el-icon--right"></i>
                </span>
                <el-dropdown-menu>
                  <!-- 新增 -->
                  <el-tooltip class="item" effect="dark" content="添加子节点" placement="top">
                    <el-button
                      icon="el-icon-plus"
                      size="large"
                      circle
                      title="添加子节点"
                      @click="handleAdd(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="查看详情" placement="top">
                    <!-- 查看 -->
                    <el-button
                      icon="el-icon-document"
                      size="large"
                      circle
                      title="查看节点详情"
                      @click="handleLook(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="编辑节点" placement="top">
                    <el-button
                      icon="el-icon-edit"
                      size="large"
                      circle
                      title="编辑节点"
                      @click="handleEdit(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="删除节点" placement="top">
                    <el-button
                      icon="el-icon-delete"
                      size="large"
                      circle
                      title="删除节点"
                      @click="handleDeletetree(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </div>
        </el-tree>
      </div>
      <!-- </div>
      </div> -->
    </el-col>
    <!--    <el-col :span="18">-->
    <!--      <div class="app-container">-->
    <!--        <div class="filter-container">-->
    <!--          <div class="filter-item">-->
    <!--            <span class="span">API名称 </span>-->
    <!--            <el-input v-model="listQuery.apiName" placeholder="请输入API名称" style="width: 200px" />-->
    <!--          </div>-->
    <!--          <div class="filter-item">-->
    <!--            <span class="span">请求方式 </span>-->
    <!--            <el-select v-model="listQuery.reqMethod" clearable placeholder="请选择请求方式" style="width: 200px">-->
    <!--              <el-option-->
    <!--                v-for="item in dictList('req_type')"-->
    <!--                :key="'type' + item.label"-->
    <!--                :label="item.label"-->
    <!--                :value="item.value" />-->
    <!--            </el-select>-->
    <!--          </div>-->
    <!--          &lt;!&ndash;      <div class="filter-item">&ndash;&gt;-->
    <!--          &lt;!&ndash;        <span>状态:</span>&ndash;&gt;-->
    <!--          &lt;!&ndash;        <el-radio&ndash;&gt;-->
    <!--          &lt;!&ndash;          v-for="item in dictList('is_release')"&ndash;&gt;-->
    <!--          &lt;!&ndash;          :key="'type' + item.label"&ndash;&gt;-->
    <!--          &lt;!&ndash;          v-model="listQuery.status"&ndash;&gt;-->
    <!--          &lt;!&ndash;          :label="item.value">&ndash;&gt;-->
    <!--          &lt;!&ndash;          {{ item.label }}&ndash;&gt;-->
    <!--          &lt;!&ndash;        </el-radio>&ndash;&gt;-->
    <!--          &lt;!&ndash;      </div>&ndash;&gt;-->
    <!--          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">-->
    <!--            {{ $t('table.search') }}-->
    <!--          </el-button>-->
    <!--        </div>-->

    <!--        <el-table-->
    <!--          ref="table"-->
    <!--          :key="tableKey"-->
    <!--          v-loading="listLoading"-->
    <!--          :data="list"-->
    <!--          border-->
    <!--          fit-->
    <!--          highlight-current-row-->
    <!--          style="width: 100%;"-->
    <!--          @selection-change="handleSelectionChange"-->
    <!--        >-->

    <!--          <el-table-column type="selection" width="55" />-->
    <!--          <el-table-column label="序号" align="center" type="index" width="60" />-->
    <!--          <el-table-column label="API名称" align="center" min-width="150px">-->
    <!--            <template slot-scope="{row}">-->
    <!--              <span>{{ row.apiName }}</span>-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column label="API版本" align="center" min-width="150px">-->
    <!--            <template slot-scope="{row}">-->
    <!--              <span>{{ row.apiVersion }}</span>-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column label="API路径" align="center" min-width="150px">-->
    <!--            <template slot-scope="{row}">-->
    <!--              <span>{{ row.apiUrl }}</span>-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column label="请求方式" align="center" min-width="150px" >-->
    <!--            <template slot-scope="{row}">-->
    <!--              <span>{{ row.reqMethod | dictLabel('req_type') }}</span>-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column label="返回格式" min-width="150px" align="center">-->
    <!--            <template slot-scope="{row}">-->
    <!--              <span>{{ row.resType | dictLabel('res_type') }}</span>-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column label="状态"  min-width="150px" align="center">-->
    <!--            <template slot-scope="{row}">-->
    <!--              <span>{{ row.status | dictLabel('is_release') }}</span>-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column label="数据源" align="center" min-width="150px">-->
    <!--            <template slot-scope="{row}">-->
    <!--              <span v-if="row.sourceName">{{ row.sourceName }}</span>-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column label="操作" align="center" min-width="230" class-name="small-padding fixed-width">-->
    <!--            <template slot-scope="{row}">-->
    <!--              <el-button v-permission="['MarketApi:MarketApi:info']" type="text" size="small" icon="el-icon-edit" @click="handleInfo(row)">-->
    <!--                详情-->
    <!--              </el-button>-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--        </el-table>-->

    <!--        <import ref="import" template-url="/MarketApi/MarketApi/template" import-url="/MarketApi/MarketApi/import" @refreshList="getList" />-->
    <!--        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" :page-sizes="pageArray" @pagination="getList" />-->

    <!--        <market-api-form ref="form" @refreshList="getList" />-->
    <!--        <market-api-info ref="info" @refreshList="getList" />-->

    <!--      </div>-->
    <!--    </el-col>-->
    <treeData ref="treeForm" @getTreeList="getTreeList" />
  </el-row>
</template>

<script>
import { deletesource, fetchsourceList, exportsource, syncsource } from '@/api/metadata/source/source'
import { fetchMasterdataDirectoryList, createMasterdataDirectory, updateMasterdataDirectory, getMasterdataDirectory, deleteMasterdataDirectory } from '@/api/masterdata/masterdataDirectory'
import Import from '@/components/Import/import'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission'
import sourceForm from './sourceCore'
import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'
import treeData from './treeData.vue'
import { fetchMarketApiList } from '@/api/marketApi/marketApi'
import marketApiInfo from './sourceCoreiInfo'
export default {
  name: 'sourceList',
  components: { sourceForm, Pagination, Import, treeData, marketApiInfo },
  directives: { waves, permission },
  data() {
    return {
      filterText: '',
      tableKey: 0,
      list: null,
      total: 0,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        sourceName: undefined,
        dbType: undefined,
        status: undefined,
        isSync: undefined,
        directoryId: '',
        page: 1,
        limit: this.$store.getters.defaultPageSize,
      },
      treeQuery: {
        tableName: undefined,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
        ancestralId: '4',
      },
      treeList: [],
      NODE_KEY: 'id', // id对应字段
      MAX_LEVEL: 5, // 设定最大层级
      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      initParam: {
        // 新增参数
        name: '新增节点',
        parentId: 0,
        children: [],
      },
      currentNodekey: '',
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },
  created() {
    this.getList()
    this.getTreeList()
  },
  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val)
    },
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getTreeList() {
      this.listLoading = true
      fetchMasterdataDirectoryList(this.treeQuery).then((response) => {
        if (response.data.code == 200) {
          this.treeList = response.data.data
          if (this.treeList.length > 0) {
            // this.listQuery.directoryId = this.treeList[0].children[0].id
            this.currentNodekey = this.treeList[0].id
            this.getList()
            this.$nextTick(() => {
              this.$refs.SlotTree.setCurrentKey(this.currentNodekey) //一定要加这个选中了否则样式没有出来
            })
          }
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getList() {
      this.listLoading = true
      fetchMarketApiList(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleCreate() {
      if (this.listQuery.directoryId) {
        this.$refs.form.handleCreate(this.listQuery.directoryId)
      } else {
        this.$refs.form.handleCreate(this.listQuery.directoryId)
      }
    },
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row.id)
    },
    handleLook(row) {
      this.$refs.form.handleLook(row.id)
    },
    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletesource(row.id).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSync(row) {
      syncsource(row.id).then((res) => {
        if (res.data.code === 0) {
          this.getList()
          this.$message.success(response.data.msg)
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletesource(this.ids).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleExport() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.downloadLoading = true
      exportsource(this.ids).then((response) => {
        this.downloadLoading = true
        if (response.data.code === 0) {
          import('@/vendor/Export2Excel').then((excel) => {
            excel.export_byte_to_excel(response.data.data.bytes, response.data.data.title)
            this.downloadLoading = false
          })
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    setSort() {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        setData: function (dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: (evt) => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
          // TODO：这里完成自己的业务处理
        },
      })
    },
    handleFilter() {
      if (this.listQuery.directoryId) {
        this.listQuery.page = 1
        this.getList()
      } else {
        this.listQuery.page = 1
        this.getList()
      }
    },
    handleNodeClick(data) {
      if (data.parentId === '0') {
        this.listQuery.directoryId = data.id
        this.getList()
      } else {
        this.listQuery.directoryId = data.id
        this.getList()
      }
    },
    handleDeletetree(_node, _data) {
      // 删除节点

      console.log(_node, _data)
      // 判断是否存在子节点
      if (_data.children && _data.children.length !== 0) {
        this.$message.error('此节点有子级，不可删除！')
        return false
      } else {
        // 删除操作
        let DeletOprate = () => {
          this.$nextTick(() => {
            if (this.$refs.SlotTree) {
              deleteMasterdataDirectory(_data.id).then((res) => {
                this.$message.success('删除成功！')
                this.$refs.SlotTree.remove(_data)
              })
            }
          })
        }

        // 二次确认
        let ConfirmFun = () => {
          this.$confirm('是否删除此节点？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              DeletOprate()
            })
            .catch(() => {})
        }

        // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
        _data[this.NODE_KEY] < this.NODE_ID_START ? DeletOprate() : ConfirmFun()
      }
    },
    handleInput(_node, _data) {
      // 修改节点
      console.log(_node, _data)

      // updateMasterdataDirectory(obj).then(res=>{
      //   if(res.data.code==0){
      //     this.$message.success(res.data.msg)
      //     this.getTreeList()
      //   }else{
      //     this.$message.error(res.data.msg)
      //   }
      // })
      // 退出编辑状态
      if (_node.isEdit) {
        this.$set(_node, 'isEdit', false)
      }
    },
    handleLook(_node, _data) {
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description,
        sort: _data.sort,
      }
      this.$refs.treeForm.handleLook(obj, this.treeQuery.ancestralId)
    },
    handleEdit(_node, _data) {
      // 编辑节点
      console.log(_node, _data)
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description,
        sort: _data.sort,
      }
      this.$refs.treeForm.handleUpdate(obj, this.treeQuery.ancestralId)
      // // 设置编辑状态
      // if(!_node.isEdit){
      // 	this.$set(_node, 'isEdit', true)
      // }

      // // 输入框聚焦
      // this.$nextTick(() => {
      // 	if(this.$refs['slotTreeInput'+_data[this.NODE_KEY]]){
      // 		this.$refs['slotTreeInput'+_data[this.NODE_KEY]].$refs.input.focus()
      // 	}
      // })
    },
    handleAdd(_node, _data) {
      // 新增节点
      console.log(_node, _data)
      // // 判断层级
      if (_node.level >= this.MAX_LEVEL) {
        this.$message.warning('当前已达到' + this.MAX_LEVEL + '级，无法新增！')
        return false
      }
      // 参数修改
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = _data.id // 父id
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      this.$refs.treeForm.handleCreate(obj, this.treeQuery.ancestralId)
      // 判断字段是否存在
      // if(!_data.children){
      // 	this.$set(_data, 'children', [])
      // }
      // 展开节点
      // if(!_node.expanded){
      // 	_node.expanded = true
      // }
    },
    handleAddTop() {
      // 添加顶部节点
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = 0
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      // console.log(obj,'顶部参数')
      this.$refs.treeForm.handleCreate(obj, this.treeQuery.ancestralId)
    },
    handleInfo(row) {
      this.$refs.info.handleInfo(row.id)
    },
  },
}
</script>
<style>
.table-expand {
  font-size: 0;
}

.table-expand label {
  width: 90px;
  color: #99a9bf;
}

.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
</style>
